package ntd.util.frame.server.util;

import cn.hutool.cache.Cache;
import cn.hutool.cache.CacheUtil;
import cn.hutool.core.lang.Opt;
import ntd.block.server.listen.ComServerListen;
import ntd.util.frame.server.context.ContextServer;
import ntd.util.frame.server.factory.FactoryComServer;

public class UtilServer {

    private static final Cache<String, ContextServer> cache = CacheUtil.newLFUCache(20);

    public static ContextServer init(ContextServer contextServer) {
        return cache.get(contextServer.getCode(), () -> FactoryComServer.initServer(contextServer));
    }

    public static void closeServer(String serverAppId) {
        Opt.ofNullable(cache.get(serverAppId)).ifPresent(contextServer -> {
            contextServer.getComServer().close();
            cache.remove(serverAppId);
        });
    }

    public static void addListen(String serverAppId, ComServerListen comServerListen) {
        Opt.ofNullable(cache.get(serverAppId)).ifPresent(contextServer -> contextServer.getComServer().addListen(comServerListen));
    }

}
